package com.lx.service.impl;

import com.lx.bean.Category;
import com.lx.vo.Node;
import com.lx.mapper.CategoryMapper;
import com.lx.service.CategoryService;
import com.lx.vo.CategoryVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public List<CategoryVo> selectCategory() {
        //获取所有的category数据
        List<Category> categories = categoryMapper.selectList(null);
        //1.筛选出一级category
        List<CategoryVo> voList = categories.stream().filter(
                category -> {
                    return category.getParentCid() == 0;
                })
                .map(
                        category -> {
                            //category对象转换为VO对象
                            CategoryVo categoryVo = new CategoryVo();
                            BeanUtils.copyProperties(category, categoryVo);
                            //2 根据一级category找到所有二级 上一级的id==下一级父id
                            //根据一级id找二级,封装到集合属性中,去categories集合中找
                            //3 根据二级菜单找到所有三级 上一级的id==下一级父id
                            categoryVo.setSonList(getSonList(categoryVo, categories));
                            return categoryVo;
                        })
                .collect(Collectors.toList());
        return voList;
    }


    private List<CategoryVo> getSonList(CategoryVo categoryVo,List<Category> categories){
        List<CategoryVo> categoryVos = categories.stream().filter(
                category -> {
                    return categoryVo.getCatId() == category.getParentCid();
                })
                .map(category -> {
                    //category对象转换为VO对象
                    CategoryVo categoryVo1 = new CategoryVo();
                    BeanUtils.copyProperties(category, categoryVo1);
                    //2 根据一级category找到所有二级 上一级的id==下一级父id
                    //根据一级id找二级,封装到集合属性中,去categories集合中找
                    //3 根据二级菜单找到所有三级 上一级的id==下一级父id
                    categoryVo1.setSonList(getSonList(categoryVo1, categories));
                    return categoryVo1;
                }).collect(Collectors.toList());
        return categoryVos;
    }



    @Override
    public List<Node> showNode() {
        List<Node> nodes = categoryMapper.selectNode();
        return nodes;
    }
}
